package com.hbk.ueditor;

import com.hbk.base.component.EnvPostProcessor;
import com.hbk.base.component.ExternalConfig;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
public class UEditorController {


    @RequestMapping("/UEditor")
    public void config(HttpServletRequest request, HttpServletResponse response){

        /**
         * 因为图片的访问前缀都是 /upload
         * 文件也是保存在 ~/upload 目录下
         * 此时得到的 rootPath 为 ~/upload
         * 所以要把 rootPath 改成上级目录
         *
         * */
        ExternalConfig.EditorConfig editorConfig = EnvPostProcessor.getExternalConfig().getEditor();
        String imgLocation = editorConfig.getImgDir();
        File file = new File(imgLocation);
        String rootPath = file.getParent();

        String action = request.getParameter("action");
        System.out.println("action:"+action);
        response.setHeader("Content-Type", "text/html");
        try {
            String exec = new ActionEnter(request,rootPath).exec();
            if(action != null &&
                    (action.equals("listfile") || action.equals("listimage"))
                    ){
                //修改文件列表和图片列表显示时的url地址
                rootPath = rootPath.replace("\\","/");
                exec = exec.replaceAll(rootPath, "");

                //读取图片列表时，如果是 // 开头，替换成 /
                exec = exec.replaceAll("//", "/");
            }

            //读取配置文件
            else if(action.equals("config")){

                //修改图片的访问前缀
                String prefix = editorConfig.getImgPrefix();
                exec = exec.replaceAll("my_img_prefix", prefix);
            }
            PrintWriter writer = response.getWriter();
            writer.write(exec);
            writer.flush();
            writer.close();
        } catch (IOException e){
            e.printStackTrace();
        }
    }
}
